<?php
class AdtypeModel extends CommonModel {
    public function __construct(){
        parent::__construct();
    }
    //获取新闻列表数据
    public function queryAdtypeList($p , $per_page = 100 , $where = array() ){
        if($p <=0 ){
            $p = 1 ;
        }
        $getwhere = " where 1 = 1 " ;
        if(isset($where['typename']) &&  $where['typename'] ){
            $getwhere.=" AND a.typename like '%{$where['typename']}%' ";
        }
        if( in_array($where['status'] , array('1', '0' ) ) ){
            $getwhere.=" AND a.status = '{$where['status']}' ";
        }
        //echo $getwhere ;
        import('Library.Page' , APP_PATH);
        $limit = ($p-1)*$per_page;
        $limit.=",{$per_page}";
        $where = '1= 1 ';
        $sql_count = "select count(*) as c from ".C("DB_PREFIX")."news as a left join ".C("DB_PREFIX")."newstype as b on a.typeid = b.id {$getwhere}" ;
        $count_data = M()->query($sql_count);
        $total = $count_data[0]['c'];

        $page = new Page($total,$per_page);
        $page_string =  $page->show();
        
        $sql = "select a.*    from ".C("DB_PREFIX")."adtype as a  {$getwhere} order by a.addtime desc  limit {$limit}" ;
      //  echo $sql;
        $list = M()->query($sql);
        
        if($list){
            foreach($list AS $k1 => $v1 ){
                if($v1['status'] == 1 ){
                    $list[$k1]['status'] = "<input type='radio' name='status[{$k1}]' checked value='1' onclick='editStatus({$v1['id']} , 1 )'>开启<input type='radio' name='status[{$k1}]' value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭";
                }else{
                    $list[$k1]['status'] = "<span style='color:red'><input type='radio' name='status[{$k1}]' value='1' onclick='editStatus({$v1['id']} , 1 )' >开启<input type='radio' name='status[{$k1}]' checked value='0' onclick='editStatus({$v1['id']} , 0 )'>关闭</span>";
                }               
                $list[$k1]['typename'] = msubstr($v1['typename'],0,20);
                $list[$k1]['addtime'] = isset($v1['addtime'])?date("Y-m-d H:i",$v1['addtime']):'' ;
                $list[$k1]['updatetime'] = isset($v1['updatetime'])?date("Y-m-d H:i",$v1['updatetime']):'' ;
                if(file_exists("./Data/Upload/Adtype/{$v1['pic']}") && $v1['pic'] != '' ){
                    $pic_url = C("upload_domain")."/Adtype/{$v1['pic']}";;
                    $list[$k1]['pic'] = "<img src='{$pic_url}' width='80' height='80'>";
                }else{
                    $list[$k1]['pic'] = '图片没有' ;
                }
                $totalAd = $this->getAdTotalByTypeid($v1['id']); 
                $url = U("ad/index" , array('typeid'=>$v1['id']) );
                $list[$k1]['typename'] = $v1['typename']."<a href='{$url}' title=\"点击查看广告{$v1['typename']}详情列表\"><font color='red'>(".$totalAd.")</a></font>";
            }
            
        }
        return array('list'=>$list , 'page_string'=>$page_string);
    }
    //根据广告类型查询多少个广告
    public function getAdTotalByTypeid($typeid){
    	return M("Ad")->where("ad_type = '{$typeid}'")->count();
    }
    //根据广告类别ID查询信息
    public function getAdtypeDataById($id){
        return M("Adtype")->where("id='{$id}'")->find();
    }
    //插入广告类型
    function insertAdtype(){
        if($_POST['info']['typename'] == '' ){
            return array('status'=>false  , 'message'=>'广告类别名称不可以为空' );
        }
        $_POST['info']['addtime'] = time();
        $_POST['info']['updatetime'] = time();
        $d = M("Adtype");
        if($row=$d->create($_POST['info'])){
            if($d->add()){
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "添加广告类别{$_POST['info']['typename']}成功" );
                return array('status'=>1 , 'message'=>'添加成功');
            }else{
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "添加广告类别{$_POST['info']['typename']}失败" );
                return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
            }
        }else{
            write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
            return array('status'=>0 , 'message'=>'数据创建失败');
        }
    }
    //修改广告类型
    function editAdtype(){
        if($_POST['info']['typename'] == '' ){
            return array('status'=>false  , 'message'=>'广告类型不可为空' );
        }
        $_POST['info']['updatetime'] = time();
        $d = M("Adtype");
        if($row=$d->create($_POST['info'])){
          // print_r($_POST['info']);
            if($d->save()){
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "修改广告类型{$_POST['info']['typename']}成功" );
                return array('status'=>1 , 'message'=>'修改成功');
            }else{
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "修改广告类型{$_POST['info']['typename']}失败" );
                return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
            }
        }else{
            write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
            return array('status'=>0 , 'message'=>'数据创建失败');
        }
    }   
    //修改状态
    public function doStatus($data = array() ){
        $d = M("Adtype");
        $num = $d->where("id = '{$data['id']}'")->save(array('status'=>$data['status'] , 'updatetime'=>time()));
        $sql = $d->getLastSql() ;
        if($num >=1 ){
            write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 1 , "修改广告类别id:{$data['id']}状态成功" );
            return array('status'=>1 , 'message'=>'修改成功');
        }
        write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 0 , "修改新闻id:{$data['id']}状态失败" );
        return array('status'=>0 , 'message'=>'修改失败你可能没有修改数据');
    }
    //更新广告缓存，根据广告类型进行更新缓存
    public function update_ad_cache($data = array() ){
    	$ids = $data['id'];
    	$res = array();
    	if($data['type'] == 0 ){
    		if(!$ids){
    			return array('status'=>0 , 'message'=>'请选择广告类型进行更新缓存');
    		}
    		$res = explode(",", $ids);
    	}else{
    		$list = M("Adtype")->field("id")->select();
    		foreach($list as $key => $val ){
    			$res[] = $val['id'];
    		}
    	}
    	if(!$res){
    		return array('status'=>0 , 'message'=>'请选择广告类型进行更新缓存');
    	}
    	foreach($res as $k => $v ){
    		cache('ad_data_'.$v,null);
    	}
    	return array('status'=>1 , 'message'=>($data['type']==0)?'更新缓存成功':'一键更新缓存成功');
    }
    //上传图片
    public function upload_adtype_pic(){
            import('ORG.Net.UploadFile');
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 3145728 ;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath =  __ROOTPATH__.'/Data/Upload/Adtype/';// 设置附件上传目录
            $upload->autoSub = true;//使用子目录保存上传文件
            $upload->subType = 'date';//使用日期模式创建子目录
            $upload->dateFormat = 'Ymd';//设置子目录日期格式
            if(!$upload->upload()) {// 上传错误提示错误信息
                return array('status' => 0 , 'message'=> $upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $info =  $upload->getUploadFileInfo();
            }
            return array('status'=>1 , 'message'=>'success' , 'pic'=>$info[0]['savename'] ) ;
            
    }
      
}
